package com.idreems.model;

import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONObject;

import android.text.TextUtils;

import com.huewu.pla.pinterest.internal.ImageWrapper;

public class QiushiLatest extends JionServerData {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String kQiushiIdKey = "id";
	private static final String kImageKey = "image";
	private static final String kThumbnailFormat = "http://img.qiushibaike.com/system/pictures/%s/%s/small/%s";
	private static final String kMiddleImageFormat = "http://img.qiushibaike.com/system/pictures/%s/%s/medium/%s";
	
	public QiushiLatest() {
		mTitle = "糗事荟萃";
		mUrl = "http://m2.qiushibaike.com/article/list/latest?count=50&page=1";
	}

	@Override
    public String url(int page) {
        if(page<=0)
        {
            page = 1;
        }
        mUrl = "http://m2.qiushibaike.com/article/list/latest?count=50&page="+page;
        return mUrl;
    }
	@Override
	public List<ImageWrapper> decode(String data) {
		List<ImageWrapper> timeline = new LinkedList<ImageWrapper>();
		if (TextUtils.isEmpty(data)) {
			return timeline;
		}
		try {
			mDescription = "content";
			mRoot = "items";

			JSONObject obj = new JSONObject(data);
			JSONArray jTimeline = obj.getJSONArray(mRoot);
			for (int i = 0; i < jTimeline.length(); i++) {
				JSONObject element = jTimeline.getJSONObject(i);
				ImageWrapper wrapper = new ImageWrapper();

				String image = element.getString(kImageKey);
				if (!TextUtils.isEmpty(image)
						&& !TextUtils.equals("null", image.toLowerCase(Locale.ENGLISH))) {
					String id = element.getString(kQiushiIdKey);
					final int RANGE_LENGTH = 4;
					String rangeId = (!TextUtils.isEmpty(id)&&id.length()>=RANGE_LENGTH)?id.substring(0,RANGE_LENGTH):"";
					wrapper.url = String.format(kThumbnailFormat, rangeId,id,image);
					wrapper.largeUrl = String.format(kMiddleImageFormat,rangeId, id,image);
				}

				wrapper.description = element.getString(mDescription);
				wrapper.id = i;
				timeline.add(wrapper);
			}
		} catch (Exception e) {
		}
		return timeline;
	}

}
